package logic

import (
	"context"
	"strconv"
	"week2_zg6/common/mysql"

	"week2_zg6/bookRpc/book"
	"week2_zg6/bookRpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type TopLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewTopLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TopLogic {
	return &TopLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *TopLogic) Top(in *book.TopRequest) (*book.TopResponse, error) {
	var str []mysql.Book
	if in.Price == "" {
		err := mysql.DB.Model(&mysql.Book{}).Order("sales desc").Limit(10).Find(&str).Error
		if err != nil {
			return nil, err
		}
	} else {
		err := mysql.DB.Model(&mysql.Book{}).Order("price desc").Limit(10).Find(&str).Error
		if err != nil {
			return nil, err
		}
	}
	var books []*book.Top
	for _, v := range str {
		books = append(books, &book.Top{
			Id:       strconv.Itoa(int(v.ID)),
			BookName: v.BookName,
			Author:   v.Author,
			Class:    v.Class,
			Title:    v.Title,
			Price:    strconv.Itoa(int(v.Price)),
			Sales:    v.Sales,
		})
	}
	return &book.TopResponse{
		Top: books,
	}, nil
}
